<template>
  <div>
    <div class="tag-box">
        <SelectedTag v-for="(tagName, tagId) in selectedTags" v-bind:key="tagId" v-bind:tagId="tagId" v-bind:tagName="tagName" v-on:removeSelectedTag="removeSelectedTag($event)"></SelectedTag>
        <span class="add-tag" data-bs-toggle="modal" data-bs-target="#staticBackdrop">+</span>
    </div>
    <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="staticBackdropLabel">检索标签</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <TagManager v-bind:selectedTags="selectedTags" v-on:addTag="addTag($event.tagId, $event.tagName)" v-on:removeSelectedTag="removeSelectedTag($event)"></TagManager>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import http from '../../utils/http.js'
  import SelectedTag from './SelectedTag'
  import TagManager from './TagManager'
  export default {
    name: 'TagDisplay',
    props: ['selectedTags', 'withBorder', 'initTagId'],
    components: {
      SelectedTag,
      TagManager,
    },
    methods: {
      /**
       * 添加标签
       * */
      addTag(tagId, name) {
        this.$set(this.selectedTags, tagId, name);
      },
      /**
       * 移除已选择的标签
       * */
      removeSelectedTag(tagId) {
        this.$delete(this.selectedTags, tagId);
      },
      /**
       * 按照给的标签id加载标签
       * */
      loadTag() {
        let initTagId = this.initTagId;
        if (initTagId && initTagId.length != 0) {
          let that = this;
          for (let i = 0; i < initTagId.length; i++) {
            let id = initTagId[i];
            http.get('/tag/' + id, {}, function(data) {
              that.$set(that.selectedTags, id, data.completeName)
            })
          }
        }
      }
    },
    watch: {
      initTagId: {
        deep: false,
        immediate: true,
        handler: function (to, from) {
          this.loadTag();
        },
      }
    },
    mounted() {
        document.getElementById('staticBackdrop').addEventListener('shown.bs.modal', function() {
          document.getElementById('searchInput').focus();
        });
    }
  }
</script>

<style scoped>
  .tag-box {
      padding: 2px 0;
      user-select: none;
  }
  .add-tag {
      cursor: pointer;
      background-color: rgb(246, 247, 248);
      font-size: 14px;
      border-radius: 5px;
      color: #7e8c8d;
      font-weight: bolder;
  }
</style>
